package com.sqlsession;

import com.sqlsession.database.CColumn;
import com.sqlsession.database.CTable;
import com.sqlsession.database.DbType;
import com.sqlsession.filter.DbFilter;

import java.sql.SQLException;
import java.util.*;

public final class CSqlSession {

    private List<DateSource> dateSources;

    private CSqlSession(List<DateSource> dateSources) {
        this.dateSources = dateSources;
    }

    public List<CTable> getTables() throws SQLException {
        List<CTable> cTables = new LinkedList<>();
        for (DateSource next : dateSources) {
            List<CTable> selectTablesSql = next.getSelectTablesSql();
            cTables.addAll(selectTablesSql);
        }
        return cTables;
    }

    public List<CColumn> getColumns(CTable cTable) throws SQLException {
        for (DateSource dateSource : dateSources) {
            List<CColumn> columns = dateSource.getColumns(cTable);
            if (columns != null) {
                return columns;
            }
        }
        return Collections.emptyList();
    }

    public void close() {
        for (DateSource dateSource : dateSources) {
            if (dateSource != null) {
                dateSource.close();
            }
        }
    }

    public static CSqlSession openDefaultCSqlSession(SqlInfo... sqlInfos) {
        List<DateSource> dateSources = new LinkedList<>();
        for (SqlInfo sqlInfo : sqlInfos) {
            DateSource dateSource = sqlInfo.getDbType().getDateSource(sqlInfo.getHost(), sqlInfo.getPort(), sqlInfo.getUserName(), sqlInfo.getPassword(), sqlInfo.getName(), sqlInfo.getFilter(),sqlInfo.getDesc());
            dateSources.add(dateSource);
        }
        return new CSqlSession(dateSources);
    }


    public static CSqlSession openDefaultCSqlSession(DbType dbType, String host, String port, String user, String password, String name, DbFilter filter,String desc) {
        DateSource dateSource = dbType.getDateSource(host, port, user, password, name, filter,desc);
        return new CSqlSession(Arrays.asList(dateSource));
    }
}
